<template>
  <view class="shop">
    <LocationCalendar @isCollectChange="isCollectChange" :shopId="shopID" :shopImg="shopInfo.head_imgs" :shopIsCollect="shopInfo.is_collect" page="shop" @search="search"/>
    <view class="content">
      <!-- 店铺信息 -->
			<ShopInfo :shop="shopInfo" @shopEva="switchTap('3')" />
      <!-- switch bar -->
      <view class="switch-bar" :style="{top:top}">
        <view class="switch-item" @tap="switchTap('1')" :class="switchValue=='1'?'a-switch-item':''"> 店铺产品 </view>
        <view class="switch-item" @tap="switchTap('2')" :class="switchValue=='2'?'a-switch-item':''"> 商家信息 </view>
        <view class="switch-item" @tap="switchTap('3')" :class="switchValue=='3'?'a-switch-item':''"> 用户评价 </view>
      </view>
      <!-- 店铺产品 -->
      <view class="shop-product" v-if="switchValue == '1'">
        <scroll-view scroll-y="true" class="tab-bar" :style="{maxHeight:h}">
          <view 
						class="tab-item" 
						:class="item.id == categoryId?' a-tab-item':''" 
						v-for="(item, index) in categoryList" 
						:key="item"
						@tap="tapCategory(item.id)"
					>
						{{item.title}}
					</view>
        </scroll-view>
        <scroll-view scroll-y="true" class="sc-view-right" :style="{maxHeight:h}" @scrolltolower="scrolltolower">
          <GoodsCard  @add="addGoods(index)" @sub="subGoods(index)" :goodsInfo="item" v-for="(item, index) in goodsList" :key="item" v-if="goodsList.length" />
					<view class="empty" v-else>
						<image src="/static/icon/components/empty.png" class="e-img"/>
						<view class="txt"> 商家还未发布此类商品~ </view>
					</view>
        </scroll-view>
        <view class="mb" v-if="shopInfo.open_status == 2"> </view>
      </view>
      <!-- 商家信息 -->
      <view class="shop-details" v-if="switchValue == '2'">
        <view class="item">
          <view class="label"> 营业时间 </view>
          <view class="value"> {{shopInfo.open_time}}至{{shopInfo.over_time}}</view>
        </view>
        <view class="item">
          <view class="label"> 联系电话 </view>
          <view class="value"> {{shopInfo.help_mobile}}</view>
        </view>
        <view class="item">
          <view class="label"> 商家地址 </view>
          <view class="value"> 
            {{shopInfo.detail_address}}
            <image src="/static/icon/shop/nav.png" class="v-img"/>
          </view>
        </view>
        <view class="item">
          <view class="label"> 商家简介 </view>
          <view class="value"> {{ shopInfo.intro }}</view>
        </view>
      </view>
      <!-- 用户评价 -->
      <Evaluate :isTab="false" :isTitle="false" :evaList="evaList" v-if="switchValue == '3'"/>
    </view>
    <!-- 底部按钮 -->
    <BtnBox 
      :goods="cartList" 
      :cartNum="cartNumber" 
      :cartPrice="cartPrice" 
      @goResult="goResult" 
      @emptyCart="emptyCart" 
      v-if="shopInfo.open_status==1"
    />
    <!-- 商品规格弹窗 -->
    <GoodsArguments ref="goodsArgumentsRef" :params="specParams" @addToCart="addToCart"/>
  </view>
</template>

<script setup>
  import { computed, ref } from 'vue';
	import { onLoad, onShow, onReachBottom } from '@dcloudio/uni-app'
  import LocationCalendar from '@/components/LocationCalendar.vue'
  import GoodsCard from '@/components/GoodsCard.vue';
  import Evaluate from '@/components/Evaluate.vue';
  import GoodsArguments from '@/components/GoodsArguments.vue';
	import ShopInfo from './components/ShopInfo.vue';
	import BtnBox from './components/BtnBox.vue';
	import { useAddressStore, useCartStore, useUserStore } from '@/store/index.js'
	import { 
		DelToCartApi,
		AddToCartApi,
		GetCartListApi ,
		GetShopDetailsApi, 
		GetShopCategoryApi, 
		GetShopGoodsListApi, 
		GetShopEvaluateListApi, 
	} from '@/service/index.js'
  const { safeArea } = uni.getSystemInfoSync()
  const switchValue = ref('1')
  const goodsArgumentsRef = ref()
  const h = computed(() => (safeArea.height - 100 - safeArea.top) + 'px' )
  const top = computed(() => safeArea.top + 'px' )
	const shopID = ref() // 店铺ID
	const shopInfo = ref({
		open_time: '', // 营业时间
		over_time: '', // 结束时间
		open_status: '',// 营业状态==1营业中 ==2 休息中
		is_collect: 0, // ==1 已收藏 ==0未收藏
		comment_score: '', // 评分
		name: '', // 
		contacts: '',// 联系人名字
		mobile: '', 
		help_mobile: '', // 客服电话 (展示给客户的)
		describe_text: '', // 店铺描述
		intro: '', // 店铺简介 (展示给客户的)
		detail_address: '',
		logo: '',
		head_imgs: [], // 商家门店照片 (展示给客户的)
		type: '', // 	1 个人 2公司
		comment_num: '', //评价数量
		goods_sales: '', // 销量
		distance: '', // 距离 米
		head_imgs: '', // 商家门店照片 (展示给客户的)
		bgc: '', // 自己转换的商家背景图
 	})
  const page = ref(1)
	const pageSize = ref(150)
	const total = ref(0)
	const cartList = ref([])
  const evaList = ref([])
	const cartPrice = ref(0)
	const cartNumber = ref(0)
	const goodsList = ref([]) // { restrict_num: '', // 限购数量 num: 0, // 自己定义的加入购物车数量 }
	const categoryId = ref('') // 分类id
	const categoryList = ref([{id:'', title: '全部商品'}]) // 分类列表
	const specParams = ref()  // 传递给规格组建的数据(商品信息)
  const searchVal = ref('')
  const search = (val) => {
    categoryId.value = ''
    searchVal.value = val
    page.value = 1
    goodsList.value = []
    getGoodsList()
  }
	// 点击切换商家产品/商家信息/评价
  const switchTap = (index) => {
    if(switchValue.value == index) return
    switchValue.value = index
    if(index == 3) getShopEvaList()
  }
  // 获取商家评价列表
  const getShopEvaList = () => {
    GetShopEvaluateListApi({shop_id: shopID.value}).then(res => {
      evaList.value = res.data
    })
  }
	// 点击收藏图标
	const isCollectChange = (is_collect) => {
		shopInfo.value.is_collect = is_collect
	}
  // 点击商品加号购物车加一 
	const tapGoodsIndex = ref()
  const addGoods = (index) => {
		tapGoodsIndex.value = index
		// 判断是否是多规格商品
		if(goodsList.value[index].speceAll) {
			specParams.value = goodsList.value[index]
			setTimeout(() => {
				goodsArgumentsRef.value.open()
			}, 0)
			return
		}
		// 判断是否超出限购
		if(goodsList.value[index].restrict_num!==0&&goodsList.value[index].restrict_num==goodsList.value[index].num) return getApp().globalData.toast('该商品限购' + goodsList.value[index].restrict_num)
		let params = {
			sku: goodsList.value[index].sku,
			num: 1
		}
		AddToCartApi(params).then(res => {
			goodsList.value[index].num = goodsList.value[index].num + 1
			getCartList()
		})
  }
	// 点击商品减号购物车减一 
	const subGoods = (index) => {
		let params = {
			sku: goodsList.value[index].sku,
			num: -1
		}
		AddToCartApi(params).then(res => {
			goodsList.value[index].num = goodsList.value[index].num - 1
			getCartList()
		})
	}
	// 多规格商品加入购物车
	const addToCart = (params) => {
		AddToCartApi(params).then(res => {
			goodsList.value[tapGoodsIndex.value].num = goodsList.value[tapGoodsIndex.value].num + 1
			goodsArgumentsRef.value.close()
			getCartList()
		})
	}
	const emptyCart = () => {
		getCartList()
		goodsList.value.forEach(item => {
			item.num = 0
		})
	}
	// 去结算
	const goResult = () => {
		let params = []
		cartList.value.forEach(item => {
			params.push({
				goods_item_id: item.shop_goods_item_id,
				num: item.num,
				goods_name: item.goods_name
			})
		})
		uni.navigateTo({
			url: `/pages/orderConfirm/orderConfirm?params=${JSON.stringify(params)}&shop_id=${shopID.value}`
		})
	}
	// 获取当前商铺的购物车信息
	const getCartList = () => {
		let params = { shop_id: shopID.value }
		GetCartListApi(params).then(res => {
			if(res.items) {
				let cartNum = 0
				res.items[0].goods.forEach(item => {
					cartNum = cartNum + item.num
				})
				cartList.value = res.items[0].goods
				cartNumber.value = cartNum
				cartPrice.value = res.pay_amount
			} else {
				cartList.value = []
				cartNumber.value = 0
				cartPrice.value = 0
			}
		})
	}
	//  获取店铺详情
	const getShopDetails = () => {
    const { lonlat } = useAddressStore()
		let params = {
			shop_id: shopID.value,
			longitude: lonlat.longitude,
			latitude: lonlat.latitude
		}
		GetShopDetailsApi(params).then(res => {
			shopInfo.value = res
			shopInfo.value.bgc = res.head_imgs[0].url
			getCategoryList()
			getGoodsList()
		})
	}
	// 获取分类
	const getCategoryList = () => {
		let params = {
			shop_id: shopID.value,
			goods_type: 1
		}
		GetShopCategoryApi(params).then(res => {
			categoryList.value.push(...res.data)
		})
	}
	// 点击分类
	const tapCategory = (id) => {
		page.value = 1
		goodsList.value = []
		categoryId.value = id
		getGoodsList()
	}
	// 获取商品
	const getGoodsList = () => {
		const { lonlat } = useAddressStore()
		let params = {
			page: page.value,
			page_size: pageSize.value,
			latitude: lonlat.latitude,
			longitude: lonlat.longitude,
			filters: {
				goods_type: 1,
				shop_id: shopID.value,
				category_id: categoryId.value,
				active: '1',
				status: 'checked',
				search: searchVal.value
			}
		}
		GetShopGoodsListApi(params).then(res => {
			res.data.forEach(item => {
				item.num = 0
			})
			goodsList.value.push(...res.data)
			goodsList.value.forEach(item => {
				cartList.value.forEach(cart => {
					if(item.spu == cart.spu) {
						item.num = item.num + cart.num
					}
				})
			})
			total.value = res.total
		})
	}
	// 滑动到底时间
	const scrolltolower = () => {
		if (total.value<=page.value*20) return
		page.value = page.value + 1
		console.log('scrolltolower');
	}
	// 获取评价
	onLoad((e) => {
		const { shop_id } = e
		shopID.value = shop_id
		getShopDetails()
	})
	onShow(() => {
		const { token } = useUserStore()
		if(token) getCartList()
	})
	onReachBottom(() => {
		if(page.value*pageSize.value>=total.value) return
		page.value = page.value + 1
		getGoodsList()
	})
</script>

<style lang="scss" scoped>
  .shop {
    width: 100%;
    .content {
      width: 100%;
      // transform: translateY(-120px);
      box-sizing: border-box;
      margin-top: -120px;
      padding-bottom: 60px;
      // switch bar
      .switch-bar {
        display: flex;
        height: 40px;
        margin-top: 10px;
        background-color: #FFFFFF;
        border-bottom: 1px solid #E6E6E6;
        border-radius: 10px 10px 0px 0px;
        box-sizing: border-box;
        position: sticky;
        left: 0;
        z-index: 999;
        .switch-item {
          flex: 1;
          font-size: 14px;
          color: #555555;
          line-height: 40px;
          text-align: center;
          &.a-switch-item {
            position: relative;
            font-weight: 500;
            font-size: 16px;
            color: #FF3B1E;
            &::before {
              position: absolute;
              bottom: 0;
              left: 50%;
              transform: translateX(-50%);
              display: block;
              content: '';
              width: 26px;
              height: 4px;
              border-radius: 33px;
              background: linear-gradient(360deg, #FF8508 0%, #FF4847 100%);
            }
          }
        }
      }
      // 店铺产品
      .shop-product {
        display: flex;
        position: relative;
        .mb {
          position: absolute;
          width: 100%;
          height: 100%;
          background-color: #fff;
          opacity: .5;
        }
        .tab-bar {
          width: 86px;
          .tab-item {
            height: 46px;
            color: #666666;
            font-size: 14px;
            font-weight: 400;
            line-height: 46px;
            text-align: center;
            &.a-tab-item {
              background: #FFFFFF;
              font-weight: 500;
              font-size: 14px;
              color: #333333;
            }
          }
        }
        .sc-view-right {
          flex: 1;
          background-color: #ffffff;
					.empty {
						text-align: center;
						.e-img {
							width: 160px;
							height: 160px;
						}
						.txt {
							color: #999999;
							font-size: 12px;
							margin-top: 14px;
							font-weight: 400;
							line-height: 14px;
						}
					}
        }
      }
      // 商家信息
      .shop-details {
        width: 100%;
        padding: 10px 23px;
        box-sizing: border-box;
        background-color: #ffffff;
        .item {
          &:nth-of-type(1) {
            .label {
              margin-top: 0;
            }
          }
          .label {
            color: #333333;
            font-size: 14px;
            font-weight: 400;
            line-height: 20px;
            margin: 14px 0 6px;
          }
          .value {
            color: #999999;
            font-size: 14px;
            font-weight: 400;
            line-height: 20px;
            .v-img {
              width: 12px;
              height: 16px;
              margin-left: 8px;
            }
          }
        }
      }
      // 用户评价
    }
    // .btn-box {
    //   position: fixed;
    //   bottom: 0;
    //   left: 0;
    //   right: 0;
    //   background-color: #fff;
    //   display: flex;
    //   justify-content: space-between;
    //   align-items: center;
    //   width: 100%;
    //   height: 50px;
    //   padding: 0 12px;
    //   box-sizing: border-box;

    //   .bot-cart {
    //     position: relative;
    //     width: 29px;
    //     height: 29px;
    //     display: flex;
    //     justify-content: center;
    //     align-items: center;

    //     .tips-num {
    //       position: absolute;
    //       right: -50%;
    //       top: 0;
    //       transform: translate(-50%, -50%);
    //       width: 16px;
    //       height: 16px;
    //       background: #F53F3F;
    //       border-radius: 50%;
    //       color: #ffffff;
    //       text-align: center;
    //       font-weight: 500;
    //       font-size: 12px;
    //       color: #FFFFFF;
    //       line-height: 16px;
    //     }
    //   }

    //   .bot-price-btn {
    //     display: flex;
    //     align-items: end;

    //     .bot-price {
    //       font-weight: 400;
    //       font-size: 14px;
    //       color: #666666;

    //       text {
    //         font-weight: 700;
    //         font-size: 14px;
    //         color: #FF3B1E;

    //         text {
    //           font-weight: 700;
    //           font-size: 20px;
    //           color: #FF3B1E;
    //         }
    //       }
    //     }

    //     .btn {
    //       width: 102px;
    //       height: 40px;
    //       color: #FFFFFF;
    //       font-size: 16px;
    //       font-weight: 400;
    //       text-align: center;
    //       line-height: 40px;
    //       background: #FF3B1E;
    //       margin-left: 10px;
    //       border-radius: 99px;
    //     }
    //   }
    // }
  }
</style>